package com.chat.controller;

import com.chat.domain.dto.ChatQueryDTO;
import com.chat.domain.pojo.Chat;
import com.chat.service.UserService;
import com.chat.util.Result;
import com.chat.util.SecurityHolderUtil;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * 聊天控制器
 *
 * @author wb
 * @since 2024-09-13
 */

@RestController
@RequestMapping("chat")
public class ChatController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    // 查询聊天列表
    @GetMapping("/list")
    public Result<Object> chats(ChatQueryDTO chatQueryDTO) {
        return Result.ok(userService.getChats(chatQueryDTO));
    }

    // 查询聊天详情
    @GetMapping("/get/{chatId}")
    public Result<Chat> get(@PathVariable String chatId, HttpSession session) {

        Chat chat = userService.getChatInfo(chatId, session);
        int userId=  SecurityHolderUtil.getUserId(session);
        String key = getUnreadCountKey(userId, chat.getReceiverId(), false);
        redisTemplate.delete(key);
        String key2 = getUnreadCountKey(userId, chat.getReceiverId(), true);
        redisTemplate.delete(key2);
        return Result.ok(chat);
    }

    // 删除聊天
    @GetMapping("/delete/{chatId}")
    public Result<Boolean> delete(@PathVariable String chatId) {
        return Result.ok(userService.deleteChat(chatId));
    }

    // 批量删除聊天
    @GetMapping("/batch-delete")
    public Result<Boolean> getMessage(String str) {
        return Result.ok(userService.batchDeleteChat(str));
    }
    private String getUnreadCountKey(Integer receiverId, Integer chatId, boolean isGroup) {
        return isGroup ? "unread:group:" + receiverId + ":" + chatId : "unread:private:" + receiverId + ":" + chatId;
    }
}
